import webUrl from './url.js'
import $tools from './tools.js'
import crypt from '@/common/js/crypt.js';
const ajax = (url, data, successCallback, failCallBack, type) => {
	var token = uni.getStorageSync('token');
	// var userId = uni.getStorageSync('USERID');
	if(url == "/userinfo/app/getUnlimitedQRCode"){
		var responseType = 'arraybuffer';
	}else{
		var responseType = '';
	}
	// 不加token白名单
	const whiteList = ['/api/common/imgCode/createImgCode','/api/common/smsCode/sendSmsCodeOnly','/api/user/login/userRegister','/api/user/login/userLogin']
		// console.log(whiteList.includes(url))
	if(!whiteList.includes(url)){
		data.token = token;
	}
	
	let cryptmsg = crypt.EncryptKey(data);
	// console.log(data,'cryptmsg',cryptmsg)
	uni.request({
		url: webUrl.webUrl + url,
		data: cryptmsg.cryptdata,
		// data: data,
		method: type || 'POST',
		dataType: 'json',
		responseType: responseType,
		// header: headerObj,
		header: {
			"x-requested-with": "XMLHttpRequest",
			"content-type": "application/json; charset=utf-8",
			// "content-type": "application/x-www-form-urlencoded",
			// "token": token,
			// "userId": userId,
			"key":cryptmsg.key
		},
		success: (res) => {
			if(url == "/api/common/imgCode/createImgCode"){
				successCallback(res.data);
			}else{
				var code = res.data.code;
				if (res.data.success == true) {
					successCallback(res.data);
				} else {
					if (code == 'code_999990') {
						if (getApp().globalData.is_flag) { 
							getApp().globalData.is_flag = false;
							console.log('token失效');
							uni.removeStorageSync('token');
							$tools.toastRedirectTo(res.data.msg, '/pages1/firtPage/firtPage');
							setTimeout(() => {
								getApp().globalData.is_flag = true;
								// console.log(getApp().globalData.is_flag);
							}, 1000)
						}
					}if (code == 'code_999177') {
						failCallBack(res.data);
					}
					else{
						$tools.toast(res.data.msg);
					}
				} 
			}
		},
		fail: () => {
			// this.$tools.toast('连接失败,请稍后再试');
			$tools.toast('请稍后再试');
		}
	})
}
export default ajax